<template>
    <div class="cardContent">
        <a-button type="primary" @click="openOutboundDraw">出库申请</a-button>
        <a-table :dataSource="outboundBillList"
                 :columns="columns"
                 :pagination="false"
                 style="margin-top: 10px"
                 bordered>
            <template #bodyCell="{text,record,index,column}">
                <template v-if="column.key == 'status'">
                    <a-tag v-if="text == 0" color="processing">
                        <template #icon>
                            <sync-outlined :spin="true"/>
                        </template>
                        审批中
                    </a-tag>
                    <a-tag v-if="text == 1" color="success">
                        <template #icon>
                            <check-circle-outlined/>
                        </template>
                        审批通过
                    </a-tag>
                    <a-tag v-if="text == 2" color="error">
                        <template #icon>
                            <close-circle-outlined/>
                        </template>
                        被驳回
                    </a-tag>
                </template>
                <a-space v-if="column.key == 'action'">
                    <a-popconfirm
                            title="删除数据无法恢复，请确认是否删除？"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button v-if="record.status == 1" type="danger">删除</a-button>
                    </a-popconfirm>
                    <a-button type="primary"
                              @click="checkAuditTrail(record.id)">
                        查看审核记录
                    </a-button>
                </a-space>
            </template>
        </a-table>
        <a-config-provider :locale="locale">
            <a-pagination style="margin-top: 10px; text-align: right"
                          v-model:current="pagination.current"
                          v-model:pageSize="pagination.pageSize"
                          show-quick-jumper
                          show-size-changer
                          :total="pagination.total"
                          :show-total="total => `总 ${total} 条数据`"
                          :page-size-options="pageSizeOptions"
                          @change="onChange"/>
        </a-config-provider>
    </div>
    <!--    发起出库申请-->
    <a-drawer
            title="填写出库信息"
            :width="700"
            :visible="outboundDrawVisible"
            :body-style="{ paddingBottom: '40px' }"
            :footer-style="{ textAlign: 'right' }"
            @close="outboundDrawVisible = false"
    >
        <a-form :model="outboundBill" layout="vertical">
            <a-row>
                <a-form-item label="处理人">
                    <a-input v-model:value="loginUser.username" disabled></a-input>
                </a-form-item>
            </a-row>
            <a-row>
                <a-col :span="12">
                    <a-form-item label="关联销售单" v-bind="validateInfos.salesOrderId">
                        <a-select :field-names="{label: 'title', value: 'id'}"
                                  placeholder="请选择关联销售单"
                                  v-model:value="outboundBill.salesOrderId"
                                  @change="onSelected"
                                  :options="salesOrderList"></a-select>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="10">
                    <a-form-item label="标题" v-bind="validateInfos.title">
                        <a-input v-model:value="outboundBill.title" placeholder="请输入标题"/>
                    </a-form-item>
                </a-col>
                <a-col :span="10">
                    <a-form-item label="产品名称">
                        <a-input v-model:value="product.name" disabled/>
                    </a-form-item>
                </a-col>
                <a-col :span="4">
                    <a-form-item label="出库数量">
                        <a-input-number addon-after="件" v-model:value="outboundBill.quantity" disabled/>
                    </a-form-item>
                </a-col>
            </a-row>

            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="描述" name="remark">
                        <a-textarea v-model:value="outboundBill.remark" :rows="5"/>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <template #footer>
            <a-space>
                <a-button type="default" @click="outboundDrawVisible = false">取消</a-button>
                <a-button type="primary" @click="outboundApply">申请</a-button>
            </a-space>
        </template>
    </a-drawer>
    <!--    查看请假详情-->
    <a-drawer
            title="出库申请单"
            :width="1000"
            :visible="outboundVisible"
            :body-style="{ paddingBottom: '40px' }"
            :footer-style="{ textAlign: 'right' }"
            @close="outboundVisible = false"
    >
        <a-form :model="drawerData.billInfo" layout="vertical">
            <a-row :gutter="16">
                <a-col :span="8">
                    <a-form-item label="申请人">
                        <a-input v-model:value="drawerData.billInfo.username" disabled/>
                    </a-form-item>
                </a-col>
                <a-col :span="16">
                    <a-form-item label="关联销售单">
                        <a-input v-model:value="drawerData.billInfo.salesOrderTitle" disabled/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="标题" name="title">
                        <a-input v-model:value="drawerData.billInfo.title" disabled/>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="产品名称">
                        <a-input v-model:value="drawerData.billInfo.productName" disabled/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="6">
                    <a-form-item label="出库数量" name="status">
                        <a-input-number disabled addon-after="件"
                                        v-model:value="drawerData.billInfo.quantity"></a-input-number>
                    </a-form-item>
                </a-col>
                <a-col :span="6">
                    <a-form-item label="状态" name="status">
                        <a-tag v-if="drawerData.billInfo.status == 2" color="warning">
                            <template #icon>
                                <exclamation-circle-outlined/>
                            </template>
                            被驳回
                        </a-tag>
                        <a-tag v-else-if="drawerData.billInfo.status == 0" color="processing">
                            <template #icon>
                                <sync-outlined :spin="true"/>
                            </template>
                            审批中
                        </a-tag>
                        <a-tag v-else color="success">
                            <template #icon>
                                <check-circle-outlined/>
                            </template>
                            审批通过
                        </a-tag>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="描述" name="remark">
                        <a-textarea :disabled="true" v-model:value="drawerData.billInfo.remark" :rows="3"/>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <a-list
                item-layout="horizontal"
                size="large"
                style="margin-top: 10px"
                bordered
                :data-source="drawerData.comments"
        >
            <template #header>
                <div>批注列表</div>
            </template>
            <template #renderItem="{ item, index }">
                <a-list-item>
                    <a-list-item-meta>
                        <template #title>
                            {{ item.username }}({{item.roleName}})
                        </template>
                        <template #avatar>
                            <a-avatar :src="item.pic"/>
                        </template>
                        <template #description>{{item.fullMessage}}</template>
                    </a-list-item-meta>
                    <div>
                        {{formatDate(item.time)}}
                    </div>
                </a-list-item>
            </template>
        </a-list>

    </a-drawer>
</template>

<script>
    import {ref, onMounted} from 'vue'
    import axios from 'axios'
    import {Form, message} from 'ant-design-vue'
    import store from '@/store'
    import dayjs from 'dayjs'
    import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
    import {CheckCircleOutlined, CloseCircleOutlined, SyncOutlined} from "@ant-design/icons-vue";

    export default {
        name: "outboundBill",
        components: {
            CloseCircleOutlined,
            SyncOutlined,
            CheckCircleOutlined
        },
        setup() {
            const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                },
                {
                    title: '标题',
                    dataIndex: 'title',
                    key: 'title',
                },
                {
                    title: '产品',
                    dataIndex: 'productName',
                    key: 'productName',
                },
                {
                    title: '数量',
                    dataIndex: 'quantity',
                    key: 'quantity',
                },
                {
                    title: '审批进度',
                    dataIndex: 'taskName',
                    key: 'taskName',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                },
                {
                    title: '操作员',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '操作',
                    key: 'action',
                }
            ]
            const commentColumns = [
                {
                    title: '时间',
                    dataIndex: 'time',
                    key: 'time',
                },
                {
                    title: '批注人',
                    dataIndex: 'userId',
                    key: 'user',
                },
                {
                    title: '批注信息',
                    dataIndex: 'fullMessage',
                    key: 'fullMessage',
                },
            ]

            const locale = zhCN
            const loginUser = ref({})
            const outboundBill = ref({
                salesOrderId: undefined,
                title: ''
            })
            const outboundBillList = ref()
            const product = ref({})
            const salesOrder = ref({})
            const salesOrderList = ref([])
            const pagination = ref({
                current: 1,
                pageSize: 5,
            })
            const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])

            const outboundVisible = ref(false)
            const outboundDrawVisible = ref(false)
            const drawerData = ref({})

            const useForm = Form.useForm
            const {validate, validateInfos, resetFields, validateField, rulesRef} = useForm(outboundBill, ref({
                salesOrderId: [{required: true, message: '请选择销售单', trigger: ['change']}],
                title: [{required: true, message: '请输入标题', trigger: ['change']}],
            }))

            const load = (pageNum) => {
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('/outbound-bill/queryPage', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    outboundBillList.value = rs.data.records
                    pagination.value.total = rs.data.total
                })
            }

            const onChange = (pageNum, pageSize) => {
                pagination.value.current = pageNum
                pagination.value.pageSize = pageSize
                load()
            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('outbound-bill/deleteById/' + id).then(rs => {
                    if (rs.code == 200) {
                        message.success("删除成功")
                        load(1)
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const checkAuditTrail = (id) => {
                axios.get('process/auditTrail/outbound/' + id).then(rs => {
                    drawerData.value = rs.data
                    outboundVisible.value = true
                })
            }

            const openOutboundDraw = () => {
                resetFields()
                axios.get('sales-order/queryNotOutbound').then(rs => {
                    salesOrderList.value = rs.data
                })
                outboundDrawVisible.value = true
            }

            const onSelected = (val, option) => {
                salesOrder.value = option

                axios.get('product/queryById/' + option.productId).then(rs => {
                    product.value = rs.data
                    if (product.value.num < option.quantity) {
                        message.warn(product.value.name + "的库存数量不满足该销售单的出库需求！")
                        outboundBill.value = {}
                    } else {
                        outboundBill.value.productId = product.value.id
                        outboundBill.value.quantity = option.volume
                    }
                })
            }

            const outboundApply = () => {
                validate().then(() => {
                    console.log("校验通过")
                    outboundBill.value.userId = loginUser.value.id
                    console.log("请假单信息：", outboundBill.value)

                    axios.post('outboundProcess/startProcess', outboundBill.value).then(rs => {
                        if (rs.code == 200) {
                            message.success("成功发起请假申请，请您耐心等待审批")
                            outboundDrawVisible.value = false
                            load()
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })


            }

            const formatDate = (time) => {
                return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
            }

            onMounted(() => {
                loginUser.value = store.state.user
                load()
            })
            return {
                columns,
                commentColumns,
                pagination,
                onChange,
                load,
                okDelete,
                outboundBill,
                outboundBillList,
                checkAuditTrail,
                outboundVisible,
                drawerData,
                locale,
                formatDate,
                pageSizeOptions,
                openOutboundDraw,
                outboundDrawVisible,
                outboundApply,
                loginUser,
                salesOrderList,
                onSelected,
                product,
                salesOrder,
                validateInfos
            }
        }
    }
</script>

<style scoped>
    .cardContent {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }
</style>